<template>
  <div class="doubleHome">
    <teamName></teamName>
    <!-- 添加个人信息 -->
    <van-collapse v-model="activeNames">
      <van-collapse-item class="title" title-class="titleColor" title="添加个人信息" name="1">
        <van-cell-group>
          <van-cell title="姓名" class='cell'>
            <template slot="">
              <van-field class="input" v-model="user.name" maxlength="8" placeholder="请输入姓名" clearable input-align="right" />
            </template>
          </van-cell>
          <van-cell title="年龄" class='cell'>
            <template slot="">
              <van-field class="input" v-model="user.age" readonly @click="showpop"  maxlength="4" placeholder="请选择年龄" clearable input-align="right" />
            </template>
          </van-cell>
          <van-cell title="性别" class='cell' v-if="!type">
            <template slot="">
              <!-- <div class="select-box">
                <div :class="user.sex ? '':'activeSex'">
                  <i class="iconfont icon-nan "></i>
                  <span>男</span>
                </div>
                <div style="margin-left: 0.5rem" :class="user.sex ? 'activeSex':''">
                  <i class="iconfont icon-nv "></i>
                  <span>女</span>
                </div>
              </div> -->
							<van-radio-group v-model="user.sex">
							  <van-radio name="0" checked-color="#42B572" @click="UserSelectSex(0)">男</van-radio>
							  <van-radio name="1" checked-color="#42B572" @click="UserSelectSex(1)">女</van-radio>
							</van-radio-group>
						</template>
          </van-cell>
          <van-cell title="性别" class='cell' v-if="type">
            <template slot="">
              <!-- <div class="select-box">
                <div :class="{'activeSex': user.sex == '0'}" @click="UserSelectSex(0)">
                  <i class="iconfont icon-nan "></i>
                  <span>男</span>
                </div>
                <div :class="{'activeSex' : user.sex == '1'}" style="margin-left: 0.5rem" @click="UserSelectSex(1)">
                  <i class="iconfont icon-nv "></i>
                  <span>女</span>
                </div>
              </div> -->
							<van-radio-group v-model="user.sex">
							  <van-radio name="0"  @click="UserSelectSex(0)" checked-color="#42B572">男</van-radio>
							  <van-radio name="1"  @click="UserSelectSex(1)" checked-color="#42B572">女</van-radio>
							</van-radio-group>
            </template>
          </van-cell>
          <van-cell title="手机号码" class='cell'>
            <template slot="">
              <!-- <span style="color: #42B574;" @click="changePhone">修改</span> -->
              <van-field class="long-input" type="number" v-model="user.phone" maxlength="11" placeholder="请输入手机号"
                clearable input-align="right" />
            </template>
          </van-cell>
          <!-- 					<van-cell title="证件类型" is-link class='cell'>
						<template slot="">
							<span>身份证</span>
						</template>
					</van-cell> -->
          <van-cell title="证件号" class='cell'>
            <template slot="">
              <van-field class="long-input" v-model="user.card" maxlength="18" clearable placeholder="请输入" input-align="right" />
            </template>
          </van-cell>
          <van-cell :title="item.name" class='cell' v-for="(item, index) in userCustomize" :key="index">
            <template slot="">
              <van-field class="long-input" v-model="item.value" maxlength="18" clearable placeholder="请输入" input-align="right" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-collapse-item>
      <!-- 添加队友信息 -->
      <van-collapse-item class="title" title="添加队友信息" name="2">
        <van-cell-group>
          <van-cell title="姓名" class='cell'>
            <template slot="">
              <van-field class="input" v-model="teammate.name" maxlength="8" placeholder="请输入姓名" clearable input-align="right" />
            </template>
          </van-cell>
          <van-cell title="年龄" class='cell'>
            <template slot="">
							 <van-field class="input" v-model="teammate.age" readonly @click="showpop(1)" maxlength="4" placeholder="请选择年龄" clearable input-align="right" />
            </template>
          </van-cell>
          <van-cell title="性别" class='cell' v-if="!type">
            <template slot="">
              <!-- <div class="select-box">
                <div :class="teammate.sex ? '':'activeSex'">
                  <i class="iconfont icon-nan "></i>
                  <span>男</span>
                </div>
                <div style="margin-left: 0.5rem" :class="teammate.sex ? 'activeSex':''">
                  <i class="iconfont icon-nv "></i>
                  <span>女</span>
                </div>
              </div> -->
							<van-radio-group v-model="teammate.sex">
							  <van-radio name="0" checked-color="#42B572" @click="teammateSelectSex(0)">男</van-radio>
							  <van-radio name="1" checked-color="#42B572" @click="teammateSelectSex(1)">女</van-radio>
							</van-radio-group>
						</template>
          </van-cell>
          <van-cell title="性别" class='cell' v-if="type">
            <template slot="">
              <!-- <div class="select-box">
                <div :class="{'activeSex': teammate.sex == '0'}" @click="teammateSelectSex(0)">
                  <i class="iconfont icon-nan "></i>
                  <span>男</span>
                </div>
                <div :class="{'activeSex' : teammate.sex == '1'}" style="margin-left: 0.5rem" @click="teammateSelectSex(1)">
                  <i class="iconfont icon-nv "></i>
                  <span>女</span>
                </div>
              </div> -->
							<van-radio-group v-model="teammate.sex">
							  <van-radio name="0" checked-color="#42B572" @click="teammateSelectSex(0)">男</van-radio>
							  <van-radio name="1" checked-color="#42B572" @click="teammateSelectSex(1)">女</van-radio>
							</van-radio-group>
            </template>
          </van-cell>
          <van-cell title="手机号码" class='cell'>
            <template slot="">
              <!-- <span style="color: #42B574;" @click="changePhone">修改</span> -->
              <van-field type="number" class="input" v-model="teammate.phone" maxlength="11" placeholder="请输入手机号"
                clearable input-align="right" />
            </template>
          </van-cell>
          <!-- 					<van-cell title="证件类型" is-link class='cell'>
						<template slot="">
							<span>身份证</span>
						</template>
					</van-cell> -->
          <van-cell title="证件号" class='cell'>
            <template slot="">
              <van-field class="long-input" v-model="teammate.card" maxlength="18" clearable placeholder="请输入"
                input-align="right" />
            </template>
          </van-cell>
          <van-cell :title="item.name" class='cell' v-for="(item, index) in teammateCustomize" :key="index">
            <template slot="">
              <van-field class="long-input" v-model="item.value" maxlength="18" clearable placeholder="请输入" input-align="right" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-collapse-item>
    </van-collapse>
    <div class="confirm" style="position: relative;">
			<van-checkbox v-model="read" checked-color="#07c160" @change="readrule" style="position: absolute;left: 0.2rem;top: -0.2rem;">同意<span style="color: #42B574;text-decoration: underline;">《防疫提醒和报名须知》</span></van-checkbox>
      <div class="confirmBtn" @click.stop="confirmPay" v-if="!Pay">确认并缴费</div>
      <div v-if="Pay" class="pay-box">
        <div>
          支付：<span style="color: red" v-if="is_pay == 1">已支付</span>
          <span style="color: red" v-if="is_pay == 0">未支付</span>
        </div>
        <div class="pay-box-method">
          <!-- 选择支付方式： -->
          <div class="wechat" @click="weixinPay">微信支付</div>
          <!-- <div class="alipay">支付宝支付</div> -->
        </div>
      </div>
    </div>
		<van-popup v-model="showrule" :style="{ height: '60%',width:'80%'}" class="notice">
			<div class="article" style="padding: .5rem;text-align: left;">
				<h3 style="text-align: center;margin: 0.3rem 0;">防疫提醒和报名须知</h3>
				{{rule}}
			</div>
		</van-popup>
		<van-popup  v-model="show" position="bottom" :style="{ height: '30%' }"  >
			<van-picker
			  title="请选择年龄"
			  show-toolbar
				:loading="load"
				:swipe-duration = "1500"
			  :columns="team?columns:columns1"
			  @confirm="onConfirm"
			  @cancel="onCancel"
			  @change="onChange"
				ref="picker"
			/>
		</van-popup>
  </div>
</template>

<script>
  import teamName from './formTitle'
  import formItem from './formItem'
  import {
    mapGetters,
    mapState
  } from 'vuex'
  export default {
    name: "doubleHome",
    data() {
      return {
				noread:true,
				showrule:false,
				read:'',
				rule:'',
        activeNames: ['1'],
        Pay: false,
        is_pay: null,
        showAreaSelect: false,
				show:false,
				columns:[],
				columns1:[],
				load:false,
				team:false,//true 队友信息 false个人信息
        user: {
          name: "",
          age: "",
          sex: '0',
          phone: "",
          card: "",
          regist_num: "",
          province: "",
          customize: []
        },
        teammate: {
          name: "",
          age: "",
          sex: '0',
          phone: "",
          card: "",
          regist_num: "",
          province: "",
          customize: []
        },
        userCustomize: [],
        teammateCustomize: [],
        sign_up_click: true
      };
    },
    computed: {
      ...mapGetters([
        'GET_SEX',
      ]),
      type() {
        let type = this.$route.query.projectType == '混双' ? true : false
        return type
      }
    },
    created() {
			this.rule = '（一）为配合疫情防控要求，本次赛事需遵守地方防疫政策。（二）所有参赛选手须在报名前确定“健康码”须符合比赛地健康码“绿码”且体温正常（37.3℃以下），无相关症状（干咳、乏力、咽痛、腹泻）的要求方可报名参赛。（三）比赛当天参赛选手“健康码”需为绿码且健康状况正常，须科学佩戴口罩（比赛期间可不佩带），赛前检录经测量体温正常（37.3℃以下），方可进入集结区及各功能区。（四）既往新冠肺炎确诊病例、疑似病例、无症状感染者及其密切接触者、确诊病例处于出院后的隔离医学观察期、无症状感染者处于解除隔离治疗或集中隔离医学观察后的医学观察随访期、入境后集中隔离医学观察期、不能提供相关证明材料等情况的人员，不得参加比赛。（五）所有的参赛选手都须遵从赛事组委会的防疫要求，否则将取消参赛资格。（六）如国内疫情出现新的变化，组委会将根据新的疫情防控要求对赛事做进一步调整'
			this.userInfo()
      this.sign_up_info()
			this.setAge()
			// console.log(this.user)
    },
    components: {
      formItem,
      teamName
    },
    methods: {
			// 阅读报名须知
			readrule(){
				this.showrule=true
				this.noread = !this.noread 
			},
			showpop(type){
				this.show = true
				if(type==1){
					this.team = true
				}else{
					this.team = false
				}
				setTimeout(()=>{
					this.$refs.picker.setColumnIndex(0,14)
				},100)
			},
			setAge(){
				this.load = true
				// let age = 4+(Math.random()*94-4)
				var arr = []
				for (var i=4;i<=90; i++){
					arr.push(i.toString())
				}
				this.columns = arr
				this.columns1 = arr
				this.load = false
			},
			onConfirm(value, index) {
				// Toast(`当前值：${value}, 当前索引：${index}`);
				if(this.team){
					this.teammate.age = value
				}else{
					this.user.age = value
				}
				this.show = false
			},
			onChange(picker, value, index) {
				// Toast(`当前值：${value}, 当前索引：${index}`);
				// this.user.age = value
				// console.log(this.user.age)
			},
			onCancel() {
				// Toast('取消');
				this.show = false
			},
      UserSelectSex(type) {
				let matchType = this.$route.query.projectType
				// console.log(type)
				if(matchType.indexOf('男')!='-1'&&type==1){
					this.$toast('该比赛仅限男性运动员参加')
					return
				}else if(matchType.indexOf('女')!='-1'&&type==0){
					this.$toast('该比赛仅限女性运动员参加')
					return
				}else{
					console.log(type)
					if(type==this.user.sex){
					}else{
						this.user.sex = type
					}
				}
      },
      teammateSelectSex(type) {
				console.log(type)
				let matchType = this.$route.query.projectType
					if(matchType.indexOf('男')!='-1'&&type==1){
						console.log(1)
						this.$toast('该比赛仅限男性运动员参加')
						return
					}else if(matchType.indexOf('女')!='-1'&&type==0){
						console.log(2)
						this.$toast('该比赛仅限女性运动员参加')
						return
					}else{
						console.log(3)
						if(type==this.teammate.sex){
						}else{
							this.teammate.sex = type
						}
					}
      },
			// 提交
      confirmPay() {
        if (this.checkedUser() && this.checkedTeammate()) {
          if (this.sign_up_click) {
            this.sign_up_click = false;
            let arr = []
            let customize = []
            let teammate = []
            for (var i = 0; i < this.userCustomize.length; i++) {
              customize.push(this.userCustomize[i].value)
            }
            for (var i = 0; i < this.teammateCustomize.length; i++) {
              teammate.push(this.teammateCustomize[i].value)
            }
            this.user.customize = customize.join(',')
            this.teammate.customize = teammate.join(',')
            arr.push(this.user, this.teammate)
						arr[0].regist_num = this.teammate.regist_num
						let matchType = this.$route.query.projectType
						if(matchType.indexOf('男')!='-1'){
							console.log(arr[0].sex,arr[1].sex)
							if(arr[0].sex==1||arr[1].sex==1){
								this.$toast('该比赛仅限男性运动员参加')
								return
							}
						}else if(matchType.indexOf('女')!='-1'){
							if(arr[0].sex==0||arr[1].sex==0){
								this.$toast('该比赛仅限女性运动员参加')
								return
							}
						}else{
						}
						if(this.noread){
							this.$toast('请先同意防疫提醒和报名须知')
							return
						}
            this.$axios.post('/mobile/v1/apply/sign_up', {
                sign: arr,
                project_id: this.$route.query.project_id,
                com_id: this.$route.query.com_id,
                group_type: this.$route.query.projectType
              }, {
                headers: {
                  token: window.sessionStorage.getItem('token')
                }
              })
              .then(res => {
                if (res.data.code == 200) {
                  this.Pay = true
                  this.$toast(res.data.msg);
                }
                if (res.data.code == 400) {
                  setTimeout(() => {
                    this.sign_up_click = true;
                  }, 3000);
                  this.$toast(res.data.msg);
                }
              })
              .catch(res => {
								console.log(res)
							})
          } else {
						this.$axios('请不要重复点击')
            this.sign_up_click = true;
          }
        } else {
          this.$toast("请填写完整信息！");
          return
        }
      },
      checkedUser() {
        if (this.user.name != '' && this.user.age != '' && this.user.card != '' && this.user.phone != ''&&this.user.age != '') {
          return true
        }
        return false
      },
      checkedTeammate() {
        if (this.teammate.name != '' && this.teammate.age != '' && this.teammate.card != '' && this.teammate.phone !==''&& this.teammate.age !=='') {
          return true
        }
        return false
      },
			// 自动填充第一个人信息
			userInfo() {
			  this.$axios
			    .get('/mobile/v1/PersonalCenter/my_info', {
			      headers: {
			        token: window.sessionStorage.getItem('token')
			      }
			    })
			    .then(res => {
						console.log(res)
			      if (res.data.code == 2000) {
			        this.user = res.data.data.user_info;
							this.user.sex = this.user.sex.toString()
							this.user.card = res.data.data.user_info.id_card
							// this.user.age = '24'
			      }
			    })
			    .catch(res => {
			      //console.log(res.msg);
			    });
			},
      sign_up_info() {
        this.$axios.get('/mobile/v1/apply/sign_up_info', {
            params: {
              project_id: this.$route.query.project_id
            },
            headers: {
              token: window.sessionStorage.getItem('token')
            }
          })
          .then(res => {
						console.log(res)
            if (res.data.code == 200) {
              this.is_pay = res.data.data.is_pay
              // 							if (res.data.data.sign_info.length != 0) {
              // 								this.user = res.data.data.sign_info[0]
              // 								this.teammate = res.data.data.sign_info[1]
              // 								// this.customize = res.data.data.sign_info[0].customize
              // 							}
              // this.user = res.data.data.sign_info[0]
              // this.com = res.data.data.com
              if (!this.type) {
                // this.user.sex = this.GET_SEX
                // this.teammate.sex = this.GET_SEX
              }
              this.$axios
                .get("/mobile/v1/apply/sign_up", {
                  params: {
                    group_id: this.$route.query.project_id,
                    group_type: this.$route.query.projectType
                  },
                  headers: {
                    token: window.sessionStorage.getItem('token')
                  }
                })
                .then(res => {
                  if (res.data.code = 200) {
                    let arr = []
                    arr = res.data.data.data.get_com.require.slice(6)
                    for (var i = 0; i < arr.length; i++) {
                      this.userCustomize.push({
                        name: arr[i],
                        value: ''
                      })
                      this.teammateCustomize.push({
                        name: arr[i],
                        value: ''
                      })
                    }
                    // console.log(this.userCustomize,this.teammateCustomize)
                    // this.user = res.data.data
                  }
                })
                .catch(res => {
                  //  console.log(res.msg);
                });
            } else {}
          })
          .catch(res => {
            //  console.log(res.msg);
          })
      },
      // weixinPay() {
      // 	var params = new URLSearchParams();
      // 	params.append('project_id', this.$route.query.project_id);
      // 	this.$axios.post('/mobile/v1/Orderpay/wx_pay', params, {
      // 			headers: {
      // 				token: window.sessionStorage.getItem('token')
      // 			}
      // 		})
      // 		.then(res => {
      // 			if (res.data.code == 2000) {
      // 				this.weixinPays(res.data.data)
      // 			} else {
      // 				// Toast(res.data.message)
      // 			}
      // 		})
      // 		.catch(res => {
      // 			//  console.log(res.msg);
      // 		})
      // },
      weixinPay() {
        // var params = new URLSearchParams();
        // params.append('project_id', this.$route.query.project_id);
        this.$axios.get('/mobile/v1/Orderpay/wx_pay', {
            params: {
              project_id: this.$route.query.project_id
            },
            headers: {
              token: window.sessionStorage.getItem('token')
            }
          })
          .then(res => {
            if (res.data.code == 2000) {
              this.weixinPays(res.data.data)
            } else {
              this.$toast(res.data.message)
            }
          })
          .catch(res => {
            //  console.log(res.msg);
          })
      },
      weixinPays(data) {
        var vm = this;
        if (typeof WeixinJSBridge == "undefined") { //微信浏览器内置对象。参考微信官方文档
          console.log('not wx')
          if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', vm.onBridgeReady(data), false);
          } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', vm.onBridgeReady(data));
            document.attachEvent('onWeixinJSBridgeReady', vm.onBridgeReady(data));
          }
        } else {
          vm.onBridgeReady(data);
        }
      },
      onBridgeReady(data) {
        var vm = this;
        WeixinJSBridge.invoke(
          'getBrandWCPayRequest', {
            "appId": data.appId, //公众号名称，由商户传入
            "timeStamp": data.timeStamp, //时间戳，自1970年以来的秒数
            "nonceStr": data.nonceStr, //随机串
            "package": data.package,
            "signType": data.signType, //微信签名方式：
            "paySign": data.paySign //微信签名
          },
          function(res) {
            // alert(JSON.stringify(res))
            // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
            if (res.err_msg == "get_brand_wcpay_request:ok") {
              vm.$toast("支付成功");
              vm.$router.push('/mine/match')
            } else {
              vm.$toast("支付失败");
            }
          }
        );
      }, 
      // selectSex(type) {
      // 	this.user.sex = type
      // 	console.log(this.user.sex)
      // },
      areaChange(value) {
        console.log(value)
        this.showAreaSelect = false;
        this.user.province = `${value[0].name} ${value[1].name} ${value[2].name}`
      },
      hideAreaSelect() {
        this.showAreaSelect = false;
      },
      changePhone() {},
    }
  }
</script>

<style lang="less" scoped>
	/deep/ .notice{
		border-radius: 10px;
	}
  .title {
    text-align: left;
  }
	.van-radio{
		display: inline-block;
	}
  .title>.van-cell {
    background-color: #c0e6d1 !important;
  }

  .confirm {
    display: flex;
    justify-content: center;
    margin-top: 1rem;
  }

  .confirmBtn {
    margin: 1rem 0;
    width: 2rem;
    background: #42b574;
    color: #fff;
    height: 0.8rem;
    line-height: 0.8rem;
    font-size: 0.32rem;
  }

  .pay-box {
    margin: 0.3rem;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    height: 2rem;
    width: 100%;
    align-items: flex-start;
    font-size: 0.3rem;
    font-weight: bold;
  }

  .pay-box-method {
    display: flex;
    height: 0.7rem;
    line-height: 0.7rem;
    width: 2rem;
    margin: 0 auto;

    .wechat {
      color: #fff;
      width: 2rem;
      background: #1EA65A;
      // 			margin-right: 0.6rem;
      // 			margin-left: 0.2rem;
    }

    .alipay {
      color: #fff;
      width: 1.8rem;
      background: #1891E0;
    }
  }

  .fade-enter-active,
  .fade-leave-active {
    transition: opacity .5s;
  }

  .fade-enter,
  .fade-leave-to

  /* .fade-leave-active below version 2.1.8 */
    {
    opacity: 0;
  }

  .cell {
    text-align: left;

    .select-box {
      display: flex;
      justify-content: flex-end;
    }

    .iconfont {
      margin-right: 0.1rem;
      font-size: 0.34rem;
    }

    .activeSex {
      color: #42b574;
    }
  }

  .input {
    padding: 0;
    float: right;
    width: 2rem;
  }

  .short-input {
    padding: 0;
    float: right;
    width: 1rem;
  }

  .long-input {
    padding: 0;
    float: right;
    width: 3rem;
  }
</style>
